package com.dhms.uikit.deviceCategory

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.widget.SearchView
import com.dhms.uikit.databinding.ItemChipSelectDeviceBinding
import com.dhms.uikit.databinding.ViewDeviceCategoryBinding
import java.lang.reflect.Field


class DeviceCategoryView : LinearLayout {

    private lateinit var _binding: ViewDeviceCategoryBinding
    val binding get() = _binding

    //选中的设备
    private var selectDevices = mutableListOf<DeviceItem>()

    var getSelectDevices: List<DeviceItem> = mutableListOf<DeviceItem>()
        get() {
            return selectDevices
        }

    //是否开启单选模式
    var singleSelection: Boolean = false
        set(value) {
            (binding.subList.adapter as? DeviceSubCategoryListAdapter)?.singleSelection = value
            field = value
        }

    private var listener: Listener? = null

    fun setListener(listener: Listener) {
        this.listener = listener
    }

    constructor(context: Context) : super(context) {
        init(null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        init(attrs, defStyle)
    }

    private fun init(attrs: AttributeSet?, defStyle: Int) {

        _binding = ViewDeviceCategoryBinding.inflate(LayoutInflater.from(context))
        addView(binding.root)

        binding.mainList.adapter = DeviceCategoryListAdapter {
            listener?.clickCategoryItem(it)
            filterCategoryState(it.ct_id)
        }
        binding.subList.adapter = DeviceSubCategoryListAdapter {
            tapDeviceItem(it)
        }

        binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(p: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(p: String?): Boolean {
                binding.categorySublistData = null
                filterCategoryState(-1)
                listener?.filterDeviceData(p)
                return false
            }
        })

        //去掉搜索框的横线
        try {        //--拿到字节码
            val argClass: Class<*> = binding.searchView.javaClass
            //--指定某个私有属性,mSearchPlate是搜索框父布局的名字
            val ownField: Field = argClass.getDeclaredField("mSearchPlate")
            //--暴力反射,只有暴力反射才能拿到私有属性
            ownField.setAccessible(true)
            val mView = ownField.get(binding.searchView) as View
            //--设置背景
            mView.setBackgroundColor(Color.TRANSPARENT)


        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun attachCategoryData(categories: List<DeviceCategoryItem>?) {
        if (categories == null || categories.isEmpty()) {
            binding.mainList.visibility = View.GONE
            binding.subList.visibility = View.GONE
            binding.emptyView.linearEmpty.visibility = View.VISIBLE

        } else {
            binding.mainList.visibility = View.VISIBLE
            binding.subList.visibility = View.VISIBLE
            binding.emptyView.linearEmpty.visibility = View.GONE
        }
        binding.categorylistData = categories
    }

    private fun filterCategoryState(selectID: Int) {
        binding.categorylistData?.forEach {
            it.checkable = it.ct_id == selectID
        }
        binding.mainList.adapter?.notifyDataSetChanged()
    }

    //点击设备
    private fun tapDeviceItem(item: DeviceItem) {
        if (item.checkable) {
            selectDevices.add(item)
            //如果是单选，则把选中的设备返回
            if (singleSelection) {
                listener?.selectDeviceItem(item)
                return
            }
        } else {
            println("删除元素前:$selectDevices")
            val m = selectDevices.firstOrNull { it.de_id == item.de_id }
            if (m != null) {
                selectDevices.remove(m)
            }
            println("删除元素后:$selectDevices")
        }
        loadSelectDevices()
    }

    fun attachSubCategoryData(subCategories: List<DeviceSubCategoryItem>, ct_id: Int) {
        //把之前选中的设备状态带回来
        selectDevices.forEach { deviceItem ->
            subCategories.forEach { subCategoryItem ->
                subCategoryItem.items?.firstOrNull { it.de_id == deviceItem.de_id }?.checkable =
                    true
            }
        }
        loadSelectDevices()
        binding.categorySublistData = subCategories
    }

    fun resetView() {
        filterCategoryState(-1)
        selectDevices.forEach {
            it.checkable = false
        }
        selectDevices.clear()
        loadSelectDevices()
        binding.categorySublistData?.forEach {
            it.items?.forEach { deviceItem ->
                deviceItem.checkable = false
            }
        }
        binding.categorySublistData = null
        binding.subList.adapter?.notifyDataSetChanged()
    }

    fun setSelectDevices(devices: List<DeviceItem>?) {
        selectDevices.clear()
        devices?.forEach { it.checkable = true }
        devices?.let {
            selectDevices.addAll(it)
        }
        loadSelectDevices()
        binding.subList.adapter?.notifyDataSetChanged()
    }

    private fun loadSelectDevices() {
        val group = binding.chipGroup

        group.removeAllViews()
        selectDevices.forEach {
            val deviceItem = it
            val chip = ItemChipSelectDeviceBinding.inflate(LayoutInflater.from(group.context))
            chip.chipItem.tag = deviceItem.de_id
            chip.chipItem.setOnCloseIconClickListener {
                deviceItem.checkable = false
                tapDeviceItem(deviceItem)
                binding.subList.adapter?.notifyDataSetChanged()
            }
            chip.chipItem.text = it.de_name
            group.addView(chip.root)
        }
        chipGroupStyle(group.childCount)
    }

    private fun chipGroupStyle(selectCount: Int) {
        val h = if (selectCount > 0) 12f else 0f
        val layoutParams = binding.placeView.layoutParams
        layoutParams.height = dip2px(context, h)
        //选中的设备，需要在上边展示
        binding.placeView.layoutParams = layoutParams
        binding.deviceDivider.visibility = if (selectCount > 0) View.VISIBLE else View.GONE
    }

    interface Listener {
        fun clickCategoryItem(item: DeviceCategoryItem)
        fun filterDeviceData(name: String?)
        fun selectDeviceItem(item: DeviceItem) {
            println("selectDeviceItem")
        }
    }
}

fun dip2px(context: Context, dipValue: Float): Int {
    val scale = context.resources.displayMetrics.density
    return (dipValue * scale + 0.5f).toInt()
}


